package com.bhxx.run;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.bhxx.entity.Property;
import com.bhxx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component("startupRunner")
public class StartupRunner implements CommandLineRunner,ServletContextListener{

	private ServletContext application=null;

	@Autowired
	private CarouselArticleService carouselArticleService;

	@Autowired
	private CourseService courseService;

	@Autowired
	private CourseTypeService courseTypeService;

	@Autowired
	private PropertyService propertyService;

	@Autowired
	private LinkService linkService;

    @Autowired
	private MenuService menuService;

	@Autowired
    private FootMenuService footMenuService;

	
	@Override
	public void run(String... args) throws Exception {
		this.loadData();
	}
	
	/**
	 * 加载数据到applicaton缓存中
	 */
	public void loadData(){
		List<Property> propertyList = propertyService.list(); // 获取所有系统属性
		Map<String,String> propertyMap=new HashMap<>();
		for(Property p:propertyList){
			propertyMap.put(p.getKey(),p.getValue());
		}
		application.setAttribute("propertyMap", propertyMap); // 所有系统属性 Map类型
        application.setAttribute("menuList", menuService.list()); // 查询所有菜单信息
		application.setAttribute("footMenuList", footMenuService.list()); // 查询所有底部菜单信息
		application.setAttribute("carouselArticleList", carouselArticleService.list()); // 查询轮播帖子
		application.setAttribute("courseHktjList",courseService.listHktj()); // 查询前10条好课推荐
		application.setAttribute("courseZxkcList",courseService.listZxkc()); // 查询前10条最新课程
		application.setAttribute("courseMfkcList",courseService.listMfkc()); // 查询前10条免费课程
		application.setAttribute("courseSzkcList",courseService.listSzkc()); // 查询前10条实战课程

		application.setAttribute("linkList",linkService.list(null)); // 查询所有友情链接

		application.setAttribute("courseTypeList",courseTypeService.list()); // 查询所有课程类别
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		application=sce.getServletContext();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

}
